import { useDictStore } from '@/store/dict';
import { ElTag, ElText } from 'element-plus';
import { PropType } from 'vue';
import { ISliceData } from './type';
import { useFormMode } from '@/components/base/Form/mode';

export const ConditionSlice = defineComponent({
  props: {
    conjs: {
      type: Array as PropType<string[]>,
      default: () => []
    },
    splitIndexes: {
      type: Array as PropType<number[]>,
      default: () => []
    }
  },
  emits: ['update:slices'],
  setup(props, { emit }) {
    const formMode = useFormMode();
    const conjs = ref([] as string[]);
    if (props.conjs) {
      conjs.value = [...props.conjs];
    }
    let slices: number[] = [];
    if (props.splitIndexes) {
      slices = [...props.splitIndexes];
    }

    const { dictConjOptions } = useDictStore();
    const dictConjOptionsMap = computed(() => {
      let map: any = {};
      dictConjOptions.forEach((item) => {
        map[item.value] = item.label;
      });
      return map;
    });

    const sliceData = ref<ISliceData[]>([]);

    const handleClick = (index: number) => {
      if (formMode?.mode !== 'edit') return;
      let i = slices.indexOf(index);
      if (i !== -1) {
        slices.splice(i, 1);
      } else {
        slices.push(index);
      }

      sliceData.value = buildSliceData(conjs.value, slices);
      emit('update:slices', slices);
    };

    /**
     * 构建条件嵌套数据
     * @param conjs 辑连接符数组
     * @param slices 切割索引数组
     * @returns 条件嵌套数据
     */
    const buildSliceData = (conjs: string[], slices: number[]) => {
      // 要显示的条件嵌套数组
      let arr = [];
      // 条件嵌套数组长度
      const len = conjs.length + 1;
      if (slices && slices.length) {
        // 计算方向 true：算左括号，false：算右括号
        let direction = true;
        for (let index = 0; index < len; index++) {
          // 是否显示左括号
          let start = false;
          // 是否显示右括号
          let end = false;
          // 显示逻辑运算符
          let operator = index < len - 1 ? conjs[index] : '';

          // 计算是否显示左括号
          if (index === 0) {
            // 第0个元素显示左括号
            start = true;
          } else if (direction) {
            // 方向为 算左括号时，切割数组存在该索引，则显示左括号
            let sliceIndex = slices.findIndex((slice: number) => slice === index);
            start = sliceIndex === -1 ? false : true;
          }
          // 改变计算方向
          if (start) direction = false;

          // 计算是否显示右括号
          if (index === len - 1) {
            // 最后一个元素显示右括号
            end = true;
          } else if (!direction) {
            // 方向为计算右括号时，切割数组存在该索引，则显示右括号
            let sliceIndex = slices.findIndex((slice: number) => slice === index + 1);
            end = sliceIndex === -1 ? false : true;
          }
          // 改变计算方向
          if (end) direction = true;

          // 计算完毕，添加数据
          arr.push({
            start,
            end,
            operator
          });
        }
      } else {
        for (let index = 0; index < len; index++) {
          arr.push({
            start: false,
            end: false,
            operator: index < len - 1 ? conjs[index] : ''
          });
        }
      }
      return arr;
    };

    sliceData.value = buildSliceData(conjs.value, slices);

    watch(
      () => [props.conjs, props.splitIndexes],
      () => {
        if (props.conjs) {
          conjs.value = [...props.conjs];
        } else {
          conjs.value = [];
        }
        if (props.splitIndexes) {
          slices = [...props.splitIndexes];
        } else {
          slices = [];
        }
        sliceData.value = buildSliceData(conjs.value, slices);
      },
      { immediate: true, deep: true }
    );

    return () => (
      <>
        {conjs.value.length > 0 && (
          <div class={'flex items-top p-0'}>
            <div class={'shrink-0 flex items-center h-34px'}>
              <ElText>条件嵌套：</ElText>
            </div>

            <div class="flex items-center  flex-wrap">
              {sliceData.value.map((item, index) => {
                return (
                  <div class="flex items-center ">
                    <div class={'flex items-center w-8 justify-center'}>
                      {item.start && <span class={'font-bold'}>{'('}</span>}
                    </div>
                    <div class="flex items-center w-40px justify-center">
                      <ElTag
                        class={{ 'cursor-pointer': formMode?.mode === 'edit' }}
                        onClick={() => {
                          handleClick(index);
                        }}>
                        {index + 1}
                      </ElTag>
                    </div>
                    <div class={'flex items-center w-8 justify-center'}>{item.end && <span class={'font-bold'}>{')'}</span>}</div>
                    <span class="mx-1">{dictConjOptionsMap.value[item.operator]}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </>
    );
  }
});
